#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <openssl/sha.h>
#include <chrono>
#include <random>

using namespace std;

// 将字节数组转换为十六进制字符串
string bytesToHex(const unsigned char* data, size_t length) {
    stringstream ss;
    for (size_t i = 0; i < length; ++i) {
        ss << hex << setw(2) << setfill('0') << (int)data[i];
    }
    return ss.str();
}

// 计算哈希值
string calculateSHA256(const string& input) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256_ctx;
    SHA256_Init(&sha256_ctx);
    SHA256_Update(&sha256_ctx, input.c_str(), input.size());
    SHA256_Final(hash, &sha256_ctx);
    return bytesToHex(hash, SHA256_DIGEST_LENGTH);
}

// Proof of Work (工作量证明)
void proofOfWork(const string& message, int difficulty) {
    string target = string(difficulty, '0');  // 创建目标前导零字符串
    int nonce = chrono::system_clock::now().time_since_epoch().count() % 1000000;  // 使用时间戳生成初始nonce值
    string hash;

    // 循环直到找到符合条件的哈希值
    do {
        nonce++;
        string data = message + to_string(nonce);
        hash = calculateSHA256(data);
    } while (hash.substr(0, difficulty) != target);  // 检查是否满足条件

  
    cout << "Message: " << message << endl;
    cout << "Nonce: " << nonce << endl;
    cout << "Hash: " << hash << endl;
}

int main() {
    string message = "Hello, Blockchain!";  // 原始消息
    // int difficulty = 3;  // 设置难度
    int difficulty = 4;  

    proofOfWork(message, difficulty);

    return 0;
}
